package cn.ycoz.cloud.windspeed.netty4;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.handler.timeout.WriteTimeoutException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpHelloWorldServerHandler extends ChannelInboundHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(HttpHelloWorldServerHandler.class);

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        logger.info("IO线程处理完毕：" + Thread.currentThread().getThreadGroup() + ":" + Thread.currentThread().getName());
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        BusinessThreadUtil.doBusiness(ctx, msg);//handle中，可以使用异步的线程池，处理业务。防止handler卡住，导致netty并发性能不佳
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (cause instanceof ReadTimeoutException || cause instanceof WriteTimeoutException) {
            logger.error("超时了：", cause);
        }
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.GATEWAY_TIMEOUT);
        ctx.writeAndFlush(response);
        ctx.close();//直接关闭channel
    }
}
//---------------------
//作者：cj2580
//来源：CSDN
//原文：https://blog.csdn.net/cj2580/article/details/78134134
//版权声明：本文为博主原创文章，转载请附上博文链接！